import {Component, OnInit} from "@angular/core";
import {Account} from "../models/account";
import {AuthService} from "../services/auth.service";
import {Router} from "@angular/router";
import {MsgResult} from "../models/msg-result";
import {AppConstants, MsgConstants} from "../constants/constants";
import {ResponseUtil} from "../util/response-util";
import {DataStorageUtil} from "../util/data-storage-util";
import {TokenUtil} from "../util/token-util";
import {LogUtil} from "../util/log-util";

@Component({
  templateUrl: './login.component.html'
})
export class LoginComponent implements OnInit {

  account: Account;
  message: string;
  isDisabled: boolean = false;

  loginMessage: string = "登录";

  constructor(private authService: AuthService,
              private router: Router,
              private responseUtil: ResponseUtil,
              private dataStorage:DataStorageUtil,
              private tokenUtil : TokenUtil,
              private logUtil: LogUtil
  ) {
  }

  ngOnInit() {
    this.account = new Account();
  }

  login(): void {
    this.loginMessage = "登录中...";
    this.isDisabled = true;
    if (!!!this.account.accountName) {
      this.isDisabled = false;
      this.loginMessage = '登录';
      this.message = "账号名为空";
      this.logUtil.info("账号名为空");
      return;
    }
    if (!!!this.account.password) {
      this.isDisabled = false;
      this.loginMessage = '登录';
      this.message = "密码为空";
      this.logUtil.info("密码为空");
      return;
    }
    this.authService.login(this.account).subscribe(
      result => this.responseUtil.success(result, this.processResult),
      error => this.responseUtil.error(error)
    );
  }

  /**
   * process result
   * @param result
   */
  private processResult = (result: MsgResult) => {
    if (!!result && result.code == MsgConstants.MSG_CODE_OK) {
      let theme = result.data.theme || 'default';
      let uri = result.data.uri || '';
      let portal = result.data.portal || 'default';

      this.dataStorage.set(AppConstants.isLogin,AppConstants.loginSucess);
      this.dataStorage.set(AppConstants.theme,theme);
      this.dataStorage.set(AppConstants.portal,portal);
      this.dataStorage.set(AppConstants.uri,uri);

      this.tokenUtil.setToken(result.data.token,result.data.refreshToken,result.data.expire);

      let home = AppConstants.homePrefix;
      if (!uri) {
        home += portal;
      } else {
        home += uri.startsWith("/") ? portal + uri : portal + "/" + uri;
      }
      this.dataStorage.set(AppConstants.home, home);
      this.redirect(home);
    } else {
      this.isDisabled = false;
      this.loginMessage = '登录';
      this.message = result.message;
    }
  }

  /**
   * redirect to the specified portal
   * @param home : /portal/default/admin/permi/accounts;mid=12
   */
  private redirect(home: string) {
    this.router.navigateByUrl(home);
  }
}
